package exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import vo.Result;

/**
 * @ClassName GlobalExceptionHandle
 * 全局异常处理器 (便捷: 在业务层中就可以不用写try/catch)
 * @Author 23207
 * @Date 2025/4/23 13:56
 * @Version 1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(Exception.class) // 捕获所有的异常
  public Result ex(Exception e) {
    e.printStackTrace();
    log.error("捕获到异常:{}", e.getMessage());
    return Result.error("对不起,操作失败,请联系管理员");
  }

  @ExceptionHandler
  public Result handleArithmeticException(DuplicateKeyException e) {
    e.printStackTrace();
    log.error("捕获到异常:{}", e.getMessage());
    // 将异常信息进行截取判断
    String message = e.getMessage();
    System.out.println("message = " + message);
    int i = message.indexOf("Duplicate entry");
    String errMsg = message.substring(i);
    String[] arr = errMsg.split(" ");
    return Result.error("用户名" + arr[2] + "已存在");
  }

  @ExceptionHandler(CustomException.class)
  public Result handleRuntimeException(CustomException ex) {
    ex.printStackTrace();
    String message = ex.getMessage();
    return Result.error(message);
  }
}